#!/usr/bin/python
# -*- coding: utf-8 -*-
# @author  : ganuoxun
# @description : 主方法
import os
import sys

import uvicorn
from fastapi import FastAPI
from starlette.responses import JSONResponse

from apps.database import mongo
from apps.global_config import configs, LOGGING_CONFIG, logger_writer
from apps.models.ResponseModel import success, error
from apps.routes.DwdRouter import router as dwd_router
from apps.routes.DwmRouter import router as dwm_router
from apps.routes.OdsRouter import router as ods_router
from apps.routes.ParserScheduled import router as parser_scheduled

app = FastAPI()

app.include_router(ods_router, tags=["ods"], prefix="/api/v1/ods")
app.include_router(dwd_router, tags=["dwd"], prefix="/api/v1/dwd")
app.include_router(dwm_router, tags=["dwm"], prefix="/api/v1/dwm")
app.include_router(parser_scheduled, tags=["parser_scheduled"], prefix="/api/v1/parser_scheduled")


# 定义全局异常处理器
@app.exception_handler(Exception)
async def handle_exception(request, exc):
    return JSONResponse(content=error(500, str(exc)), status_code=500)


@app.get("/index", tags=["Root"])
async def index():
    return success(None, "Welcome to this fantastic app!")


@app.get("/test", tags=["Root"])
async def index():
    from apps.utils.MinioBoto3 import S3Util
    return await S3Util.read_s3_data("processtxt/1/1703659582919278/10011703659582920446/KMI0010.txt")


@app.on_event('startup')
async def init_service():
    if not os.path.exists(os.path.dirname(configs.LOG_PATH)):
        os.makedirs(os.path.dirname(configs.LOG_PATH))
    sys.stdout = logger_writer
    sys.stderr = logger_writer
    # 初始化mongodb
    mongo.init(configs.MONGO_URI)


@app.on_event("shutdown")
async def shutdown():
    try:
        if mongo.client:
            mongo.client.close()
    except Exception as e:
        print(e)

    print("shutdown")


if __name__ == "__main__":
    uvicorn.run("base_main:app", host="0.0.0.0", port=configs.PORT, reload=True, log_config=LOGGING_CONFIG)
